{% extends "base.html" %}

{% block title %}创作中心 - 畅读小说网{% endblock %}

{% block content %}
<style>
    /* 整体容器样式 */
    .profile-container {
        max-width: 1200px;
        margin: 0 auto;
        padding: 20px;
    }

    /* 个人中心头部样式 */
    .profile-header {
        text-align: center;
        margin-bottom: 40px;
    }

    .profile-header h1 {
        font-size: 2.5rem;
        font-weight: bold;
        color: #333;
    }

    /* 消息提示样式 */
    .messages {
        margin-bottom: 20px;
    }

    .alert {
        padding: 10px;
        border-radius: 5px;
        margin-bottom: 10px;
    }

    .alert-success {
        background-color: #d4edda;
        color: #155724;
    }

    .alert-error {
        background-color: #f8d7da;
        color: #721c24;
    }

    /* 个人中心内容样式 */
    .profile-content {
        display: flex;
        gap: 20px;
    }

    /* 侧边栏样式 */
    .profile-sidebar {
        width: 250px;
        background-color: #f9f9f9;
        border-radius: 5px;
        padding: 20px;
        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    }

    .user-avatar {
        text-align: center;
        margin-bottom: 20px;
    }

    .user-avatar img {
        width: 100px;
        height: 100px;
        border-radius: 50%;
        object-fit: cover;
    }

    .default-avatar {
        width: 100px;
        height: 100px;
        border-radius: 50%;
        background-color: #007BFF;
        color: white;
        font-size: 2rem;
        display: flex;
        justify-content: center;
        align-items: center;
        margin: 0 auto;
    }

    .user-role {
        margin-top: 10px;
        color: #666;
    }

    .sidebar-menu ul {
        list-style-type: none;
        padding: 0;
    }

    .sidebar-menu li {
        margin-bottom: 10px;
    }

    .sidebar-menu li a {
        display: block;
        padding: 10px;
        border-radius: 5px;
        text-decoration: none;
        color: #333;
    }

    .sidebar-menu li a:hover {
        background-color: #e0e0e0;
    }

    .sidebar-menu li.active a {
        background-color: #007BFF;
        color: white;
    }

    /* 主内容样式 */
    .profile-main {
        flex: 1;
    }

    .profile-section {
        background-color: #fff;
        border-radius: 5px;
        padding: 20px;
        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        margin-bottom: 20px;
    }

    .profile-section h2 {
        font-size: 2rem;
        font-weight: bold;
        color: #333;
        margin-bottom: 20px;
    }

    /* 表单样式 */
    .form-group {
        margin-bottom: 20px;
    }

    .form-group label {
        display: block;
        font-weight: bold;
        color: #333;
        margin-bottom: 5px;
    }

    .form-group input[type="text"],
    .form-group input[type="email"],
    .form-group input[type="file"],
    .form-group textarea {
        width: 100%;
        padding: 10px;
        border: 1px solid #ccc;
        border-radius: 5px;
        outline: none;
    }

    .form-text.text-muted {
        color: #999;
        font-size: 0.9rem;
        margin-top: 5px;
    }

    /* 按钮样式 */
    .btn {
        padding: 10px 20px;
        border: none;
        border-radius: 5px;
        cursor: pointer;
        margin-right: 10px;
    }

    .btn-primary {
        background-color: #007BFF;
        color: white;
    }

    .btn-primary:hover {
        background-color: #0056b3;
    }

    .btn-secondary {
        background-color: #6c757d;
        color: white;
    }

    .btn-secondary:hover {
        background-color: #5a6268;
    }

    /* 通知样式 */
    .notification {
        position: fixed;
        top: 20px;
        right: 20px;
        padding: 15px 25px;
        border-radius: 5px;
        color: white;
        z-index: 1000;
        display: none;
    }

    .notification-success {
        background-color: #28a745;
    }

    .notification-error {
        background-color: #dc3545;
    }
</style>

<!-- 通知元素 -->
<div id="notification" class="notification"></div>

<div class="profile-container">
    <div class="profile-header">
        <h1>创作中心</h1>
    </div>

    {% if messages %}
    <div class="messages">
        {% for message in messages %}
        <div class="alert {% if message.tags %}alert-{{ message.tags }}{% endif %}">
            {{ message }}
        </div>
        {% endfor %}
    </div>
    {% endif %}

    <div class="profile-content">
        <div class="profile-sidebar">
            <div class="user-avatar">
                {% if user.avatar %}
                    <img src="{{ user.avatar.url }}" alt="{{ user.username }}">
                {% else %}
                    <div class="default-avatar">{{ user.username|first|upper }}</div>
                {% endif %}
                <div class="user-role">{{ user.get_role_display }}</div>
            </div>
            <div class="sidebar-menu">
                <ul>
                    <li><a href="{% url 'user_profile' %}">个人信息</a></li>
                    <li><a href="{% url 'change_password' %}">修改密码</a></li>
                    <li><a href="{% url 'bookshelf' %}">我的书架</a></li>
                    {% if user.role == 'reader' %}
                    <li><a href="{% url 'author_apply' %}">申请成为作者</a></li>
                    {% endif %}
                    <li class="active"><a href="{% url 'author_center' %}">作家中心</a></li>
                </ul>
            </div>
        </div>

        <div class="profile-main">
            <div class="profile-section">
                <!-- 创建表单 -->
                <div id="createForm">
                    <div class="card">
                        <div class="card-header">
                            <h5>创建新作品</h5>
                        </div>
                        <div class="card-body">
                            <form id="novelForm">
                                <div class="mb-3">
                                    <label class="form-label">书名</label>
                                    <input type="text" class="form-control" id="title" required>
                                </div>
                                <div class="mb-3">
                                    <label class="form-label">分类</label>
                                    <select class="form-select" id="category" required>
                                        <option value="">加载分类中...</option>
                                    </select>
                                </div>
                                <div class="mb-3">
                                    <label class="form-label">封面</label>
                                    <input type="file" class="form-control" id="cover" accept="image/*">
                                    <small class="form-text text-muted">建议尺寸：300×400像素，大小不超过2MB</small>
                                </div>
                                <div class="mb-3">
                                    <label class="form-label">简介</label>
                                    <textarea class="form-control" id="description" rows="3" required></textarea>
                                    <small class="form-text text-muted">至少50字，不超过500字</small>
                                </div>
                                <button type="submit" class="btn btn-primary" id="submitBtn">提交</button>
                            </form>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script src="https://cdn.bootcdn.net/ajax/libs/axios/0.21.1/axios.min.js"></script>
<script>
    const API_BASE = '/api';
    const MAX_FILE_SIZE = 2 * 1024 * 1024; // 2MB
    const NOTIFICATION_DURATION = 5000; // 5秒

    // 显示通知
    function showNotification(message, type = 'success') {
        const notification = document.getElementById('notification');
        notification.textContent = message;
        notification.className = `notification notification-${type}`;
        notification.style.display = 'block';
        
        setTimeout(() => {
            notification.style.display = 'none';
        }, NOTIFICATION_DURATION);
    }

    // 安全获取元素
    function getElement(id, errorMessage = '') {
        const element = document.getElementById(id);
        if (!element) {
            console.error(`找不到元素: ${id}`);
            if (errorMessage) showNotification(errorMessage, 'error');
            throw new Error(`找不到元素: ${id}`);
        }
        return element;
    }

    // 获取CSRF Token
    function getCSRFToken() {
        const cookieMatch = document.cookie.match(/csrftoken=([^;]+)/);
        return cookieMatch ? cookieMatch[1] : '';
    }

    // 验证文件
    function validateFile(file) {
        if (!file) return true;
        
        if (!file.type.startsWith('image/')) {
            showNotification('请上传有效的图片文件', 'error');
            return false;
        }
        
        if (file.size > MAX_FILE_SIZE) {
            showNotification('封面图片不能超过2MB', 'error');
            return false;
        }
        
        return true;
    }

    // 加载分类
    async function loadCategories() {
        try {
            const response = await axios.get(`${API_BASE}/categories/`);
            const select = getElement('category');
            
            select.innerHTML = '';
            const defaultOption = document.createElement('option');
            defaultOption.value = '';
            defaultOption.textContent = '-- 请选择分类 --';
            select.appendChild(defaultOption);
            
            response.data.results.forEach(category => {
                const option = document.createElement('option');
                option.value = category.id;
                option.textContent = category.name;
                select.appendChild(option);
            });
        } catch (error) {
            console.error('加载分类失败:', error);
            showNotification('加载分类失败，请刷新页面重试', 'error');
        }
    }

    // 创建小说
    async function createNovel() {
        const submitBtn = getElement('submitBtn');
        const originalText = submitBtn.textContent;
        
        try {
            // 禁用按钮防止重复提交
            submitBtn.disabled = true;
            submitBtn.textContent = '提交中...';
            
            // 验证表单
            const title = getElement('title').value.trim();
            const category = getElement('category').value;
            const description = getElement('description').value.trim();
            const coverFile = getElement('cover').files[0];
            
            if (!title || !category || !description) {
                throw new Error('请填写所有必填字段');
            }
            
            if (!validateFile(coverFile)) return;
            
            // 准备表单数据
            const formData = new FormData();
            formData.append('title', title);
            formData.append('category', category);
            formData.append('description', description);
            if (coverFile) formData.append('cover', coverFile);
            
            // 提交数据
            const response = await axios.post(`${API_BASE}/novels/`, formData, {
                headers: {
                    'Authorization': `Token ${localStorage.getItem('token')}`,
                    'X-CSRFToken': getCSRFToken()
                }
            });
            
            // 成功处理
            showNotification('小说创建成功，已提交审核');
            getElement('novelForm').reset();
        } catch (error) {
            console.error('创建失败:', error);
            const errorMessage = error.response?.data?.detail || 
                              error.response?.data?.message || 
                              error.message || 
                              '创建失败，请稍后重试';
            showNotification(errorMessage, 'error');
        } finally {
            submitBtn.disabled = false;
            submitBtn.textContent = originalText;
        }
    }

    // 初始化
    document.addEventListener('DOMContentLoaded', function() {
        // 加载分类
        loadCategories();

        // 表单提交
        getElement('novelForm').addEventListener('submit', function(e) {
            e.preventDefault();
            createNovel();
        });
    });
</script>
{% endblock %}    